home *** CD-ROM | disk | FTP | other *** search
- Path: dragon.solect.com!annex
- From: gallantm@kanservu.ca (Matt Gallant)
- Newsgroups: comp.lang.c++
- Subject: Re: What is referencing good for?
- Date: Mon, 26 Feb 96 06:47:21 GMT
- Organization: KanServU Bureau Aylmer, Ontario Canada
- Message-ID: <4grl0b$b2o@dragon.solect.com>
- References: <4goojd$a9g@wintermute.ecs.fullerton.edu>
- NNTP-Posting-Host: ts1p01.kanservu.ca
- Mime-Version: 1.0
- Content-Type: text/plain; charset=US-ASCII
- X-Newsreader: News Xpress 2.0 Beta #0
-
- In article <4goojd$a9g@wintermute.ecs.fullerton.edu>, grosin@titan.fullerton.edu (Gil Rosin) wrote:
- >I don't quite understand what reference functions are good for. Again, I can
- >do the same stuff with pointers.
- >
- >Can someone give me a REAL world example of where I would use referencing
- >perhaps somewhere that I can not use pointers?
- >
-
- Well, you "hit the nail on the head" when you said that you can do everything
- with pointers that you can pretty much do with references and that references
- just seem to give cleaner code.
-
- With references, you let the compiler handle all of the pointer manipulation
- and dereferencing. This was added to C++ because in C (which does not have
- references), using pointers was always the issue that seemed to cause almost
- EVERYONE problems from time to time. Programmers knew that pointers were more
- efficient, but they often made coding errors the first time around.
- References give you the efficiency automatically, without the need to remember
- to derefernce your pointers and such.
-
- References can also be used to 'alias' a variable. I've been using them in a
- program that I'm writing that uses complex unions and structures. If I need
- to access a member of a union repeatedly, I make a reference to it and use the
- reference instead of the full name. Here's an example (it's "meaning" is
- totally BOGUS, it's just a demo)...
-
- union {
- char str[4];
- DWORD dw;
- struct {
- char byte;
- short index;
- char c;
- } myStruct;
- } myUnion;
-
- Now, let's say that I need to access the 'index' member. Without pointers or
- references, I'd have to type 'myUnion.myStruct.index' every time I need to
- read or write the member.
-
- WITH POINTERS----------------------------------
- short *theShort = &myUnion.myStruct.index; // create a pointer to short
- .
- .
- .
- //To access it...
- short count = *theShort; // Read it
- *theShort = 4; // Write it
-
- WITH REFERENCES------------------------------
- short &theShort = myUnion.myStruct.index; // 'theShort' becomes an alias
- .
- .
- .
- // To access it...
- short count = theShort;
- theShort = 4;
-
- As you can see, the reference version seems more "natural".
-
- In short, whether you use one or the other, it's just a matter of personal
- preference. What's important is that C++ gives you the choice!
-
-
-
- --------------------------------------
- Matt Gallant
- Aylmer, Ontario Canada
-